using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Rensoft.CRM.Client.AccountsAPI;
using Rensoft.CRM.Client.HostingAPI;
using Rensoft.CRM.Client.Properties;
using System.Threading;

namespace Rensoft.CRM.Client.Editors
{
    public partial class AccountEditor : Rensoft.CRM.Client.Editors.BaseEditor
    {
        private Account account;
        private List<string> contactGuidList;
        private ToolStripButton addContactButton;
        private ToolStripSeparator toolStripSeparator;
        private string currency;

        protected delegate void AddContactMethod(string name, string phone, string email, string guid);

        public AccountEditor(Program program) : base(program)
        {
            InitializeComponent();
            InitializeCurrencyComboBox(currencyComboBox);

            contactGuidList = new List<string>();
            toolStripSeparator = new ToolStripSeparator();
            addContactButton = new ToolStripButton("Add Contact", Resources.Supplier);

            AddToolStripItem(toolStripSeparator, false);
            AddToolStripItem(addContactButton, false);

            SetMode(EditorMode.Create);
            Text = "New Account - " + AssemblyInfo.Title;
        }

        public AccountEditor(Program program, Account account) : this(program)
        {
            SetMode(EditorMode.Modify);
            Text = account.Title + " - " + AssemblyInfo.Title;

            this.account = account;
            codeTextBox.Text = account.Code;
            titleTextBox.Text = account.Title;

            if ((account.Types & AccountType.Client) != 0)
            {
                clientCheckBox.Checked = true;
            }

            if ((account.Types & AccountType.Supplier) != 0)
            {
                supplierCheckBox.Checked = true;
            }
        }

        protected override void PerformClear()
        {
            base.PerformClear();

            codeTextBox.ResetText();
            titleTextBox.ResetText();
            clientCheckBox.Checked = false;
            supplierCheckBox.Checked = false;

            currencyComboBox.SelectedIndex = 0;

            hostingPasswordTextBox.ResetText();
            hostingUsernameTextBox.ResetText();
        }

        protected override void PerformLoad(DoWorkEventArgs e)
        {
            switch (Mode)
            {
                case EditorMode.Modify:
                    {
                        if ((account.Types & AccountType.Client) != 0)
                        {
                            //HostingService hostingService = HostingService.CreateInstance();
                            //MethodInvoker hostingTest = new MethodInvoker(hostingService.Test);

                            //// Connection to hosting server may not be available.
                            //hostingEnableCheckBox.Enabled = false;
                            //if (Program.ConfirmConnection(hostingService, hostingTest))
                            //{
                            //    // Allow save functionality to be used.
                            //    hostingEnableCheckBox.Enabled = true;

                            //    // May have been removed outside of the application, or never created.
                            //    if (hostingService.ClientCheckGuidExists(account.AccountGuid))
                            //    {
                            //        ClientAccount client = hostingService.ClientFetchByGuid(account.AccountGuid);
                            //        hostingEnableCheckBox.Checked = true;
                            //        hostingUsernameTextBox.Text = client.PrimaryUser.Username;
                            //        hostingPasswordTextBox.Text = client.PrimaryUser.Password;
                            //    }
                            //}

                            AccountsService accountsService = AccountsService.CreateInstance();
                            string[] contactGuids = accountsService.AccountFetchContactGuids(account.AccountId);

                            contactGuidList.Clear();
                            contactGuidList.AddRange(contactGuids);
                        }
                    }
                    break;
            }

            base.PerformLoad(e);
        }

        protected override void PerformSave(DoWorkEventArgs e)
        {
            AccountsService accountsService = AccountsService.CreateInstance();
            //HostingService hostingService = HostingService.CreateInstance();
            //MethodInvoker hostingTest = new MethodInvoker(hostingService.Test);

            AccountType types = (AccountType)0;
            if (clientCheckBox.Checked) { types |= AccountType.Client; }
            if (supplierCheckBox.Checked) { types |= AccountType.Supplier; }

            string code = codeTextBox.Text;
            string username = hostingUsernameTextBox.Text;
            string password = hostingPasswordTextBox.Text;

            switch (Mode)
            {
                case EditorMode.Create:
                    {
                        if (accountsService.AccountCheckCodeExists(code))
                        {
                            MessageBox.Show(
                                "The account code '" + code + "' is already in use.",
                                "Account Code Usage", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                            return;
                        }

                        // Checkbox may be disabled if hosting service unavailable on load.
                        //if (hostingEnableCheckBox.Enabled && 
                        //    hostingEnableCheckBox.Checked &&
                        //    Program.ConfirmConnection(hostingService, hostingTest) &&
                        //    hostingService.ClientCheckUserExists(username))
                        //{
                        //    MessageBox.Show(
                        //        "The username '" + username + "' is already in use.",
                        //        "Hosting Username Usage", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //    e.Cancel = true;
                        //    return;
                        //}

                        Account account = accountsService.AccountCreate(
                            titleTextBox.Text, codeTextBox.Text, types, currency);

                        accountsService.AccountUpdateContactGuids(
                            contactGuidList.ToArray(), account.AccountId);

                        // Checkbox may be disabled if hosting service unavailable on load.
                        //if (hostingEnableCheckBox.Enabled &&
                        //    hostingEnableCheckBox.Checked &&
                        //    Program.ConfirmConnection(hostingService, hostingTest))
                        //{
                        //    hostingService.ClientCreate(
                        //        account.AccountGuid,
                        //        codeTextBox.Text,
                        //        titleTextBox.Text,
                        //        username,
                        //        password);
                        //}
                    }
                    break;

                case EditorMode.Modify:
                    {
                        accountsService.AccountUpdateContactGuids(
                            contactGuidList.ToArray(), account.AccountId);

                        // Checkbox may be disabled if hosting service unavailable on load.
                        //if (hostingEnableCheckBox.Enabled &&
                        //    Program.ConfirmConnection(hostingService, hostingTest))
                        //{
                        //    bool hostingClientExists = hostingService.ClientCheckGuidExists(
                        //        account.AccountGuid);

                        //    if ((!hostingEnableCheckBox.Checked) && hostingClientExists)
                        //    {
                        //        // Client account exists on the hosting server, and must be removed.
                        //        hostingService.ClientRemove(account.AccountGuid);
                        //    }
                        //    else if (hostingEnableCheckBox.Checked && !hostingClientExists)
                        //    {
                        //        // Client account does not exist, and must be created.
                        //        hostingService.ClientCreate(
                        //            account.AccountGuid,
                        //            codeTextBox.Text,
                        //            titleTextBox.Text,
                        //            username,
                        //            password);
                        //    }
                        //}
                    }
                    break;
            }
        }

        private void titleTextBox_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(titleTextBox.Text))
            {
                Text = titleTextBox.Text + " - " + AssemblyInfo.Title;
            }
        }

        private void hostingEnableCheckBox_CheckStateChanged(object sender, EventArgs e)
        {
            hostingUsernameTextBox.Enabled = hostingEnableCheckBox.Checked;
            hostingPasswordTextBox.Enabled = hostingEnableCheckBox.Checked;

            if (hostingEnableCheckBox.Checked &&
                string.IsNullOrEmpty(hostingUsernameTextBox.Text))
            {
                // Only set if first time edit, and hosting is enabled.
                hostingUsernameTextBox.Text = codeTextBox.Text;
            }
        }

        private void clientCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            hostingEnableCheckBox.Enabled = clientCheckBox.Checked;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            contactsLoadBackgroundWorker.CancelAsync();
            base.OnClosing(e);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            toolStripSeparator.Visible = false;
            addContactButton.Visible = false;

            switch (tabControl1.SelectedIndex)
            {
                case 1:
                    toolStripSeparator.Visible = true;
                    addContactButton.Visible = true;
                    break;
            }
        }

        private void currencyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            currency = ((CurrencyComboItem)currencyComboBox.SelectedItem).Value;
        }
    }
}